package com.leoncom.sms_silencer.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TaskDataSource {
	private SQLiteDatabase database;
	private SmsSQLiteHelper dbHelper;
	private String[] allColumns = { SmsSQLiteHelper.COLUMN_ID,
			SmsSQLiteHelper.COLUMN_HOUR, SmsSQLiteHelper.COLUMN_MIN, 
			SmsSQLiteHelper.COLUMN_PERIOD, SmsSQLiteHelper.COLUMN_REPEATED };

	public TaskDataSource(Context context) {
		this.dbHelper = new SmsSQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public SilencerTask createTask(SilencerTask task) {
		// delete old
		deleteTask();
		
		// insert new one
		ContentValues values = new ContentValues();
		values.put(SmsSQLiteHelper.COLUMN_HOUR, task.getHour());
		values.put(SmsSQLiteHelper.COLUMN_MIN, task.getMin());
		values.put(SmsSQLiteHelper.COLUMN_PERIOD, task.getPeriod());
		values.put(SmsSQLiteHelper.COLUMN_REPEATED, task.concatDaysIndexToString());
		database.insert(SmsSQLiteHelper.TABLE_TASK, null, values);

		return getTask();
	}

	public void deleteTask() {
		database.delete(SmsSQLiteHelper.TABLE_TASK, null, null);
	}

	public SilencerTask getTask() {
		Cursor cursor = database.query(SmsSQLiteHelper.TABLE_TASK, allColumns,
				null, null, null, null, null);
		cursor.moveToFirst();
		if(cursor.isAfterLast()) {
			return null;
		}
		SilencerTask newTask = cursorToTask(cursor);
		cursor.close();
		return newTask;
	}

	private SilencerTask cursorToTask(Cursor cursor) {
		SilencerTask task = new SilencerTask();
		task.setId(cursor.getLong(0));
		task.setHour(cursor.getInt(1));
		task.setMin(cursor.getInt(2));
		task.setPeriod(cursor.getInt(3));
		task.initDaysIndexFromString(cursor.getString(4));
		task.setInit(true);
		return task;
	}
}